package com.lawyer.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.lawyer.entity.Config;
import com.lawyer.entity.MoneyFlows;
import com.lawyer.entity.RegimentalMember;
import com.lawyer.entity.RiderOrder;
import com.lawyer.entity.User;
import com.lawyer.entity.view.OrderRecommendView;
import com.lawyer.model.Message;
import com.lawyer.model.MessageConstant;
import com.lawyer.repository.ConfigRepository;
import com.lawyer.repository.MoneyFlowsRepository;
import com.lawyer.repository.OrderRecommendViewRepository;
import com.lawyer.repository.RegimentalMemberRepository;
import com.lawyer.repository.RiderOrderRepository;
import com.lawyer.repository.UserRepository;

@RestController
@RequestMapping(value = "/system")
@Api(tags = "系统管理-订单管理")
@SuppressWarnings("all")
public class SystemRiderOrderController {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private RiderOrderRepository riderOrderRepository;

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private MoneyFlowsRepository moneyFlowsRepository;

	@Autowired
	private RegimentalMemberRepository regimentalMemberRepository;

	@Autowired
	private ConfigRepository configRepository;

	@Autowired
	private EntityManager entityManager;

	@Autowired
	private OrderRecommendViewRepository orderRecommendViewRepository;

	@ApiOperation(httpMethod = "GET", value = "查询订单列表", notes = "查询订单列表")
	@RequestMapping(value = "/riderOrder", method = RequestMethod.GET)
	@ApiImplicitParams({ @ApiImplicitParam(name = "page", dataType = "integer", paramType = "query", value = "第几页"),
			@ApiImplicitParam(name = "size", dataType = "integer", paramType = "query", value = "分页条数") })
	public HttpEntity<?> users(String username, String orderStatus, @PageableDefault(page = 0, sort = { "createdDate" }, direction = Sort.Direction.DESC) Pageable pageable) {
		Message msg = new Message();

		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

		CriteriaQuery<RiderOrder> criteriaQuery = criteriaBuilder.createQuery(RiderOrder.class);

		Root<RiderOrder> root = criteriaQuery.from(RiderOrder.class);

		criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createdDate")));

		// 查询条件
		List<Predicate> predicates = new ArrayList<>();

		if (StringUtils.isNotEmpty(orderStatus) && !"全部".equals(orderStatus)) {
			predicates.add(criteriaBuilder.equal(root.get("orderStatus"), orderStatus));
		}

		if (StringUtils.isNotEmpty(username)) {
			predicates.add(criteriaBuilder.equal(root.get("username"), username));
		}

		// 将所有条件用 and 联合起来
		if (!CollectionUtils.isEmpty(predicates)) {
			criteriaQuery.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])));
		}

		List<RiderOrder> counts = entityManager.createQuery(criteriaQuery).getResultList();
		TypedQuery<RiderOrder> createQuery = entityManager.createQuery(criteriaQuery);
		createQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
		createQuery.setMaxResults(pageable.getPageSize());

		Page page = new PageImpl<RiderOrder>(createQuery.getResultList(), pageable, counts.size());

		msg.setData(page);

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "GET", value = "订单详情", notes = "订单详情")
	@RequestMapping(value = "/riderOrderInfo", method = RequestMethod.GET)
	public HttpEntity<?> riderOrderInfo(Integer orderId) {
		Message msg = new Message();

		RiderOrder orderInfo = riderOrderRepository.findOne(orderId);
		User userInfo = userRepository.findOne(orderInfo.getUserId());
		orderInfo.setLeaderId(userInfo.getId());
		orderInfo.setLeaderHeaderIco(userInfo.getHeaderIco());
		orderInfo.setLeaderName(userInfo.getNickName());
		msg.setData(orderInfo);
		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "PUT", value = "更新订单状态", notes = "orderAmount:订单金额,orderStatus状态：未完成，已完成")
	@RequestMapping(value = "/updateOrderStatus", method = RequestMethod.PUT)
	public HttpEntity<?> updateOrderStatus(Integer orderId, String orderStatus,Double orderAmount) {
		Message msg = new Message();
		try {
			RiderOrder order = riderOrderRepository.findOne(orderId);
			if (order != null && !"签约完成".equals(order.getOrderStatus())) {
			
				if ("签约完成".equals(orderStatus)) {
					order.setOrderStatus(orderStatus);
					// 保存变更记录
					
					if (order.getLeaderId() != null) {
						MoneyFlows flow = new MoneyFlows();
						Config standRiderCommission = configRepository.findByName("StandRiderCommission");// 站长提成
						Config regimentalRiderCommission = configRepository.findByName("RegimentalRiderCommission");// 团长提成

						RegimentalMember leader = regimentalMemberRepository.findOne(order.getLeaderId());
						Double result = 0D;
						if (leader.getStarLevel() == 2) {// 站长
							flow.setTypeFlow(3);
							flow.setUserType("3");
							Double rate = Double.valueOf(standRiderCommission.getValue());
							result = order.getOrderAmount() * rate;

						} else if (leader.getStarLevel() == 3) {// 团长
							flow.setTypeFlow(4);
							flow.setUserType("4");
							Double rate = Double.valueOf(regimentalRiderCommission.getValue());
							result = order.getOrderAmount() * rate;
						}

						Double changeMoney = new BigDecimal(result).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
						flow.setChangeMoney(changeMoney);
						flow.setUserId(leader.getLeaderId());
						flow.setUserName(leader.getLeaderName());
						flow.setPhone(order.getPhone());
						flow.setDescription("来自:【" + order.getUsername() + "】,的拥金");
						moneyFlowsRepository.save(flow);

						User user = userRepository.findOne(leader.getId());

						double commission = new BigDecimal(user.getBalance()).add(new BigDecimal(changeMoney)).doubleValue();
						user.setBalance(commission);
						userRepository.save(user);
					}

					//推荐站长
					OrderRecommendView orderRemcommend = orderRecommendViewRepository.findOne(order.getId());

					if (orderRemcommend.getMyId() != null && "签约完成".equals(orderRemcommend.getOrderStatus())) {
						
						MoneyFlows flowRecommend = new MoneyFlows();
						
						User user = userRepository.findOne(orderRemcommend.getMyId());
						
						Config standRecommendStand = configRepository.findByName("StandRecommendStand");// 站长推荐站长提成

						flowRecommend.setTypeFlow(5);
						flowRecommend.setUserType("5");
						Double rate = Double.valueOf(standRecommendStand.getValue());
						Double result = order.getOrderAmount() * rate;

						Double changeMoney = new BigDecimal(result).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
						flowRecommend.setChangeMoney(changeMoney);
						flowRecommend.setUserId(orderRemcommend.getMyId());
						flowRecommend.setUserName(orderRemcommend.getMyName());
						flowRecommend.setPhone(order.getPhone());

						flowRecommend.setDescription("来自:【" + order.getUsername() + "】,的拥金");
						moneyFlowsRepository.save(flowRecommend);
						
						double commission = new BigDecimal(user.getBalance()).add(new BigDecimal(changeMoney)).doubleValue();
						user.setBalance(commission);
						userRepository.save(user);
					}

					riderOrderRepository.save(order);
				}

			} else {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("订单不存在");
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

}
